package com.library.common.dialog

import android.app.Dialog
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.databinding.DataBindingUtil
import com.library.common.R
import com.library.common.base.BaseActivity
import com.library.common.databinding.DialogDownappBinding
import com.library.common.util.DensityUtil
import com.library.common.util.SdCardUtil
import com.rxlife.coroutine.RxLifeScope
import kotlinx.coroutines.Dispatchers
import rxhttp.toDownload
import rxhttp.wrapper.entity.ProgressT
import rxhttp.wrapper.param.RxHttp


/**
 * 作者：SimGa
 * 日期：2019-11-18
 * 时间：14:08
 * 包名：com.seefun.app.dialog
 */
class DownAppDialog(val activity: BaseActivity<*, *>, url: String, versionCode: String) :
    Dialog(activity, R.style.Dialog) {

    private var mBinding: DialogDownappBinding? = null
//    private val DOWNLOAD_URL = "http://update.9158.com/miaolive/Miaolive.apk"
    private var versionCode = ""

    init {
        this.versionCode = versionCode
        mBinding = DataBindingUtil.inflate(
            LayoutInflater.from(context),
            R.layout.dialog_downapp,
            null,
            false
        )
        setContentView(mBinding?.root!!)
        window!!.attributes.width = DensityUtil.dip2px(258f)
        window!!.attributes.height = WindowManager.LayoutParams.WRAP_CONTENT
        setCancelable(false)
        mBinding?.tvNewVersion?.text = "v$versionCode"
        downLoad(url, {
            //下载中
            mBinding?.spbHorizontal?.progress = it.progress
            mBinding?.tvPercent?.text = "${it.progress}%"
        }, {
            //下载完成
            mBinding?.btnInstall?.visibility = View.VISIBLE
            mBinding?.clJindu?.visibility = View.GONE
        }, {
            //下载失败
            mBinding?.tvContent?.text = it.message
        })
        mBinding?.btnInstall?.setOnClickListener {
            onClickInstallApk.invoke()
        }
    }

    private fun downLoad(
        apkUrl: String,
        downLoadData: (ProgressT<String>) -> Unit = {},
        downLoadSuccess: (String) -> Unit,
        downLoadError: (Throwable) -> Unit = {}
    ) {
        RxLifeScope().launch({
            val destPath = SdCardUtil.get(context).DEFAULT_DOWNLOAD_PATH+"/"+"youyitong_$versionCode.apk"
            val downLoadPath = RxHttp.get(apkUrl).toDownload(
                destPath,
                Dispatchers.Main
            ) { progressT: ProgressT<String> ->
                //下载中回调
                downLoadData.invoke(progressT)
            }.await()
            //下载完成 回调
            downLoadSuccess.invoke(downLoadPath.toString())
        }, {
            //下载失败回调
            downLoadError.invoke(it)
        })
    }

    lateinit var onClickInstallApk:()->Unit
}
